package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Api(tags = "私信接口")
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IUserService userService;

    @ApiOperation("发送私信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接受者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("发送内容") @RequestParam("content") @NonNull String content) {
        //  1. 校验用户状态
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
        if(user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_BANNED.getMessage());
        }

        //  调用service
        messageService.create(user.getId(),receiveUserId,content);
        return AppResult.success();
    }

    @ApiOperation("获取用户未读消息数量")
    @GetMapping("/getunreadcount")
    public AppResult getUnreadCount(HttpServletRequest request) {
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);

        //  调用service
        Integer count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);
    }

    @ApiOperation("查询用户所有私信")
    @GetMapping("/getall")
    public AppResult getAll(HttpServletRequest request) {
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);

        //  调用service
        List<Message> messages = messageService.selectAllById(user.getId());
        return AppResult.success(messages);
    }

    @ApiOperation("已读私信")
    @PostMapping("/markread")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("私信id") @RequestParam("id") @NonNull Long id) {
        //  判断私信是否属于用户
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
        Message message = messageService.selectById(id);
        if(!user.getId().equals(message.getReceiveUserId())) {
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            throw new ApplicationException(ResultCode.FAILED_UNAUTHORIZED.getMessage());
        }

        //  调用service
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @ApiOperation("回复私信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("回复的私信id") @RequestParam("replyId") @NonNull Long replyId,
                           @ApiParam("私信内容") @RequestParam("content") @NonNull String content) {
        User postUser = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
        //  1. 判断用户是否被禁言
        if(postUser.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_BANNED.getMessage());
        }

        //  2. 判断 发送用户 与 接受用户 是否相同
        Message exitsMessage = messageService.selectById(replyId);
        if(exitsMessage == null || exitsMessage.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_NOT_EXISTS.getMessage());
        }
        //  2.1 此次回复的 接受用户 == 已存在私信中的发送用户
        User receiveUser = userService.selectById(exitsMessage.getPostUserId());
        if(postUser.getId().equals(receiveUser.getId())) {
            log.warn(ResultCode.FAILED.toString() + "不能回复自己");
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }

        //  3. 调用service
        messageService.reply(replyId,postUser.getId(),receiveUser.getId(),content);

        return AppResult.success();
    }
}
